package com.yc.home.cloudother.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yc.bean.Result;
import com.yc.entity.Question;
import com.yc.entity.Review;
import com.yc.home.cloudother.mapper.QuestionMapper;
import com.yc.home.cloudother.mapper.ReviewMapper;
import com.yc.home.cloudother.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lzk
 * @since 2024-09-27
 */
@RestController
@RequestMapping("/review")
public class ReviewController {

    @Autowired
    ReviewMapper reviewMapper;

    //新增题目
    @RequestMapping("addQuestion")
    public Result addQuestion(@RequestBody @Valid Review review, Errors errors, @RequestHeader(name = "Authorization") String jwt){
        Claims user;
        try {
            user = JwtUtil.parseJWT(jwt);
            // 检查JWT是否过期
            if (JwtUtil.isTokenExpired(user.getExpiration())) { // 假设JwtUtil有这样一个方法
                return new Result(-2, "JWT已过期", null);
            }
        } catch (Exception e) {
            // 解析JWT时发生的异常，可能表示JWT格式错误或已损坏
            return new Result(-2, "无效的JWT令牌", null);
        }
        Object nid = user.get("id");
        String uid = nid.toString();

        //选项选择字段判断
        if(review.getType().endsWith("选题")){
            int sum = 0;
            for (String s : review.getItems().split(";")) {
                if(s.startsWith("$")){
                    sum = sum + 1;
                }
            }
            if (sum == 0) {
                errors.rejectValue("items", "no", "请选择选项!");
            }

            if("单选题".equals(review.getType()) && sum > 1){
                errors.rejectValue("items", "no", "单选题只能一个选项!");
            }

            //不能填空值选项
            String[] split = review.getItems().split(";");
            for (String item : split) {
                // 使用 trim() 方法移除字符串前后的空格，并检查是否为空
                if (item.trim().isEmpty()) {
                    // 如果发现空字符串或仅包含空格的字符串，则退出方法或执行其他操作
                    errors.rejectValue("items", "no", "选项不能设置空!");
                    break;
                }
            }
        }

        //字段判断
        if (errors.hasErrors()) {
            return new Result(0, "有信息为空！", errors.getAllErrors());
        }

        if("判断题".equals(review.getType())){
            if(review.getItems().contains("true")){
                review.setItems("true");
            }else{
                review.setItems("false");
            }
        }

        //存入题目
        try{
            review.setStatus(0);
            review.setUid(Integer.valueOf(uid));
            reviewMapper.insert(review);
            return new Result(1, "上传成功", null);
        }catch (Exception e){
            return new Result(-1, "系统异常", null);
        }
    }

        @PostMapping("/upload")
        public Result upload(MultipartFile file) throws IOException {
            // 封装文件名称，防止名称重复
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.indexOf('.'));
            String fileName = UUID.randomUUID().toString();
            // 判断是否存在basePath,如果不存在，先创建
            String basePath = "D:/java/git/project/home/cloud-other/src/main/resources/static/image/";
            File dir = new File(basePath);
            if (!dir.exists()) {
            // 目录不存在的话，创建目录
                dir.mkdirs();
            }
            file.transferTo(new File(basePath + fileName + suffix));
            return new Result(1,"上传成功","http://127.0.0.1/cloud-other/image/"+fileName + suffix);
        }

    @RequestMapping("getreview")
    Page getreview(@RequestParam(defaultValue = "1") int currentPage4, @RequestParam(defaultValue = "10") int pagesize, String id, String content, String start, String end, String status, String types, String tname){
        Page<Review> page = new Page<>(currentPage4, pagesize);
        LambdaQueryWrapper<Review> lqw = new LambdaQueryWrapper<>();
        if(!"".equals(id)){
            lqw.eq(Review::getId, id);
        }
        if(!"".equals(content)){
            lqw.like(Review::getContent, content);
        }
        if(!"".equals(tname)){
            lqw.eq(Review::getCourse, tname);
        }
        if(!"2".equals(status)){
            lqw.eq(Review::getStatus, status);
        }
        if(!"-1".equals(types)){
            lqw.eq(Review::getType, types);
        }
        if(!"".equals(start) && !"".equals(end)){
            lqw.ge(Review::getCreateTime, start);
            lqw.le(Review::getCreateTime, end);
        }
        return reviewMapper.selectPage(page, lqw);
    }

    @RequestMapping("tono")
    Result tono(String rid){
        Review review = reviewMapper.selectById(rid);
        review.setStatus(-1);
        reviewMapper.updateById(review);
        return new Result(1, "操作成功", null);
    }

    @Autowired
    QuestionMapper questionMapper;

    @Transactional
    @RequestMapping("took")
    public Result took(@RequestBody Review review){
        try{
            Question question = new Question();
            question.setContent(review.getContent());
            question.setCourse(review.getCourse());
            question.setType(review.getType());
            question.setItems(review.getItems());
            question.setIdeas(review.getIdeas());
            question.setImage(review.getImage());
            question.setStatus(1);
            questionMapper.insert(question);
            review.setStatus(1);
            reviewMapper.updateById(review);
            return new Result(1, "操作成功", null);
        }catch (Exception e){
            return new Result(0, "系统繁忙，请稍后再试", null);
        }
    }

}

